package com.infra.server.filter;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author win
 * @date 2021/7/21 14:32
 * 响应过滤器，获取响应结果
 */
@Slf4j
@Component
public class HttpResponseFilter implements GlobalFilter, Ordered {

//    @Autowired
//    private AsyncTask asyncTask;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();

        GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT);

        DataBufferFactory bufferFactory = response.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffer);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        //释放掉内存
                        DataBufferUtils.release(join);
                        try {
                            // 保存日志到数据库
                            String s = new String(content, StandardCharsets.UTF_8);
                            JSONObject object = JSONObject.parseObject(s);

                            gatewayContext.getSysLog().setResponseCode(object.getInteger("code"));
                            gatewayContext.getSysLog().setResponseMsg(object.getString("message"));

                            // 单位毫秒
                            long betweenMs = DateUtil.betweenMs(gatewayContext.getRequestTime(), new Date());
                            gatewayContext.getSysLog().setExecutionTime(betweenMs);
                            if ("json".equals(gatewayContext.getParamsType())) {
                                gatewayContext.getSysLog().setRequestParams(gatewayContext.getCacheBody());
                            } else {
                                gatewayContext.getSysLog().setRequestParams(String.valueOf(gatewayContext.getFormData()));
                            }

//                            asyncTask.saveES(gatewayContext.getSysLog());
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                        return bufferFactory.wrap(content);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        return -200;
    }

}
